package br.com.puertorico.mecanismos.ui.listeners;

import java.util.Map.Entry;

import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;

import br.com.puertorico.common.loggin.Logger;
import br.com.puertorico.mecanismos.ui.scopes.Conversation;
import br.com.puertorico.mecanismos.ui.scopes.ConversationScope;
import br.com.puertorico.mecanismos.ui.utils.FacesUtils;

public class ConversationPhaseListener implements PhaseListener {

	private static final long serialVersionUID = 6999806499352661534L;

	private static final Logger LOGGER = Logger
			.getLogger(ConversationPhaseListener.class);

	@Override
	public void afterPhase(PhaseEvent event) {
		if (FacesUtils.getFacesContext().getViewRoot() == null) {
			return;
		}

		String currentViewId = FacesUtils.getFacesContext().getViewRoot()
				.getViewId();
		if (currentViewId.contains("publico")) {
			return;
		}

		LOGGER.info("View ID: #0", currentViewId);
		for (Entry<String, Object> e : ConversationScope
				.getConversationMBeans().entrySet()) {
			Conversation conversation = e.getValue().getClass()
					.getAnnotation(Conversation.class);
			boolean keep = false;
			for (String viewId : conversation.viewIds()) {
				if (ConversationScope.getNavigationMap().containsKey(
						viewId.trim())) {
					if (ConversationScope.getNavigationMap().get(viewId)
							.equals(currentViewId)) {
						keep = true;
						break;
					}
				}
			}
			if (!keep) {
				LOGGER.info("Removendo ConversationMBean: #0",
						conversation.id());
				ConversationScope.getConversationMBeans().remove(
						conversation.id());
			}
		}

	}

	@Override
	public void beforePhase(PhaseEvent event) {

	}

	@Override
	public PhaseId getPhaseId() {
		return PhaseId.RESTORE_VIEW;
	}

}
